package com.atguigu.day03;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple1;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;

// KeyedProcessFunction
public class Example13 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, Tuple1<String>>() {
                    @Override
                    public Tuple1<String> map(String value) throws Exception {
                        return Tuple1.of(value);
                    }
                })
                .keyBy(r -> r.f0)
                .process(new KeyedProcessFunction<String, Tuple1<String>, String>() {
                    @Override
                    public void processElement(Tuple1<String> value, Context ctx, Collector<String> out) throws Exception {
                        // 到达机器的时间
                        long ts = ctx.timerService().currentProcessingTime();
                        out.collect("数据：" + value + " 到达了！到达时间是：" + new Timestamp(ts));
                        // 注册一个10秒钟之后的定时器
                        long tenSecLater = ts + 10 * 1000L;
                        ctx.timerService().registerProcessingTimeTimer(tenSecLater);
                        out.collect("注册了一个时间戳是：" + new Timestamp(tenSecLater) + " 的定时器");
                    }

                    // 参数timestamp：注册的定时器的时间戳
                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        super.onTimer(timestamp, ctx, out);
                        out.collect("定时器触发了！触发时间是：" + new Timestamp(timestamp));
                    }
                })
                .print();

        env.execute();
    }
}
